package kd.hc.ecco;

import com.grapecity.documents.excel.Q;
import kd.bos.bill.BillShowParameter;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.exception.KDBizException;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.ShowType;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.events.HyperLinkClickArgs;
import kd.bos.form.events.SetFilterEvent;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 目标成本 列表插件
 */
public class TargetCostListPlugin extends AbstractListPlugin implements Plugin {
    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        if (e.getOperationResult() != null) {
            boolean success = e.getOperationResult().isSuccess();
            if (success) {
                switch (operateKey) {
                    case "dochage":
                        dochage(e);
                        break;
                }
            }
        }
    }

    public void dochage(AfterDoOperationEventArgs e) {
        Boolean isExitPk = false;
        BillShowParameter billShowParameter = new BillShowParameter();
        Object pk = e.getOperationResult().getSuccessPkIds().get(0);
        List<QFilter> qFilterList = new ArrayList<QFilter>();
        qFilterList.add(new QFilter("hc95_mbcbd_id", QCP.equals, pk));
        qFilterList.add(new QFilter("billstatus", QCP.in, new String[]{"A", "B"}));
        DynamicObject[] load = BusinessDataServiceHelper.load("hc95_target_costupdate", "id", qFilterList.stream().toArray(QFilter[]::new));
        if (load != null && load.length >= 1) {
            billShowParameter.setPkId(load[0].getPkValue());
            if (load.length >= 2) {
                throw new KDBizException("目标成本变更单数据异常找到两个及两个以上未完成目标成本变更单!");
            }
            isExitPk = true;
        }
        billShowParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
        billShowParameter.setFormId("hc95_target_costupdate");

        billShowParameter.setCustomParam("sourceBill", "TargetCost");
        billShowParameter.setCustomParam("pk", pk);
        billShowParameter.setCustomParam("isExitPk", isExitPk);
        getView().showForm(billShowParameter);
    }
}